<template>
  <div class="group-table-container">

    
    <el-card class="audio-group-card">
      <template #header>
        <div class="card-header">
          <h2>音频组</h2>
          <div class="header-actions">
        <!-- 添加上传音频按钮 -->
        <el-button type="primary" style="margin-top: 10px;"
        @click="openAudioUploader" :icon="Upload">上传音频</el-button>
            <span v-if="audioData.length > 0" class="selection-count">已选择 {{ selectedItems.length }} 项</span>
            <!-- 仅在URL有group_id参数时显示当前ID -->
            <span v-if="urlHasGroupId" class="group-id-display">
              当前音频组ID: {{ groupIdModel }}
            </span>
          </div>
        </div>
      </template>

      <!-- 修复标签切换问题 -->
      <div class="custom-tabs">
        <div class="tab-headers">
          <div class="tab-header" :class="{ 'active': currentTabName === 'current' }" @click="switchTab('current')">
            当前音频
          </div>
          <div class="tab-header" :class="{ 'active': currentTabName === 'history' }" @click="switchTab('history')">
            历史记录
          </div>
        </div>

        <!-- 当前选中音频标签页 -->
        <div v-show="currentTabName === 'current'" class="tab-content">
          <div v-if="audioData.length > 0">
            <el-table ref="audioTable" :data="audioData" style="width: 100%" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column label="文件名" min-width="200" show-overflow-tooltip>
                <template #default="scope">
                  <span>
                    <span class="language-tag" v-if="getLanguageTag(scope.row.meta_data)">
                      {{ getLanguageTag(scope.row.meta_data) }}
                    </span>
                    {{ scope.row.filename }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="时长" width="80">
                <template #default="scope">
                  {{ getDuration(scope.row.meta_data) }}
                </template>
              </el-table-column>
              <el-table-column label="内容摘要" min-width="220" show-overflow-tooltip>
                <template #default="scope">
                  <div>{{ getMetaDataText(scope.row.meta_data) }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="创建时间" width="180" />
              <el-table-column label="操作" width="160" fixed="right">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button size="small" type="primary" circle @click="playAudio(scope.row)" title="播放"
                      :disabled="!canPlayAudio(scope.row)">
                      <i class="el-icon-video-play">▶</i>
                    </el-button>
                    <el-button size="small" type="success" circle @click="downloadAudio(scope.row)" title="下载"
                      :disabled="!hasValidAudioPath(scope.row)">
                      <i class="el-icon-download">↓</i>
                    </el-button>
                    <el-button size="small" type="info" circle @click="previewSubtitle(scope.row)" title="预览字幕"
                      :disabled="!hasValidSubtitlePath(scope.row)">
                      <i class="el-icon-document">📄</i>
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <div class="table-actions" style="margin-top: 15px;">
              <el-button @click="selectAll" type="primary" plain>全选</el-button>
              <el-button @click="deselectAll" plain>取消全选</el-button>
              <!-- <el-button @click="clearCurrentAudioGroup" type="danger" plain>清空当前音频</el-button> -->
            </div>
          </div>
          <div v-else class="empty-state">
            <el-empty description="没有选择音频" :image-size="120">
              <template #description>
                <p>请从历史记录中选择音频文件</p>
              </template>
              <el-button type="primary" @click="switchTab('history')">
                查看历史记录
              </el-button>
            </el-empty>
          </div>
        </div>

        <!-- 历史记录标签页 -->
        <div v-show="currentTabName === 'history'" class="tab-content">
          <!-- <div class="history-search">
              <el-input
                v-model="historySearchQuery"
                placeholder="搜索音频文件"
                clearable
                prefix-icon="el-icon-search"
                style="margin-bottom: 15px;"
              />
            </div> -->

          <!-- 改为展示音频文件列表 -->
          <el-table ref="historyTable" :data="filteredHistoryAudios" style="width: 100%" @selection-change="handleHistorySelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="文件名" min-width="200" show-overflow-tooltip>
              <template #default="scope">
                <span>
                  <span class="language-tag" v-if="getLanguageTag(scope.row.meta_data)">
                    {{ getLanguageTag(scope.row.meta_data) }}
                  </span>
                  {{ scope.row.filename }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="时长" width="80">
              <template #default="scope">
                {{ getDuration(scope.row.meta_data) }}
              </template>
            </el-table-column>
            <el-table-column label="内容摘要" min-width="220" show-overflow-tooltip>
              <template #default="scope">
                <div>{{ getMetaDataText(scope.row.meta_data) }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180" />
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button size="small" type="primary" circle @click="playAudio(scope.row)" title="播放"
                    :disabled="!canPlayAudio(scope.row)">
                    <i class="el-icon-video-play">▶</i>
                  </el-button>
                  <el-button size="small" type="success" circle @click="downloadAudio(scope.row)" title="下载"
                    :disabled="!hasValidAudioPath(scope.row)">
                    <i class="el-icon-download">↓</i>
                  </el-button>
                  <el-button size="small" type="info" circle @click="previewSubtitle(scope.row)" title="预览字幕"
                    :disabled="!hasValidSubtitlePath(scope.row)">
                    <i class="el-icon-document">📄</i>
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <div class="history-actions" style="margin-top: 15px; display: flex; justify-content: space-between;">
            <div>
              <el-button @click="selectAllHistory" type="primary" plain>全选</el-button>
              <el-button @click="deselectAllHistory" plain>取消全选</el-button>
            </div>
            <el-button type="success" @click="confirmHistorySelection" :disabled="selectedHistoryItems.length === 0">
              添加到当前音频 (已选 {{ selectedHistoryItems.length }} 项)
            </el-button>
          </div>

          <div class="pagination-container" style="margin-top: 15px; display: flex; justify-content: center;">
            <el-pagination background layout="prev, pager, next" :total="paginationInfo.totalCount"
              :page-size="paginationInfo.pageSize" :current-page="paginationInfo.currentPage"
              @current-change="handleHistoryPageChange" />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 音频播放对话框 -->
    <el-dialog v-model="audioPlayerVisible" title="音频播放" width="500px" destroy-on-close>
      <div class="audio-player-container">
        <h3>
          <span class="language-tag" v-if="currentAudioFile && getLanguageTag(currentAudioFile.meta_data)">
            {{ getLanguageTag(currentAudioFile.meta_data) }}
          </span>
          {{ currentAudioFile?.filename || '未知音频' }}
        </h3>
        <audio ref="audioPlayer" controls style="width: 100%" :src="currentAudioUrl"
          @ended="audioPlayerVisible = false"></audio>
        <div class="audio-info" v-if="currentAudioFile">
          <p>{{ getMetaDataText(currentAudioFile.meta_data) }}</p>
          <p>
            <span v-if="getDuration(currentAudioFile.meta_data) !== '-'">
              时长: {{ getDuration(currentAudioFile.meta_data) }} |
            </span>
            创建时间: {{ currentAudioFile.created_at }}
          </p>
        </div>
      </div>
    </el-dialog>

    <el-dialog v-model="subtitlePreviewVisible" title="字幕预览" width="600px" destroy-on-close>
      <div class="subtitle-preview-container">
        <h3>{{ currentSubtitleFile?.filename || '字幕文件' }}</h3>
        <div v-if="subtitleLoading" class="subtitle-loading">
          <p>正在加载字幕内容...</p>
        </div>
        <div v-else-if="subtitleContent" class="subtitle-content">
          <pre>{{ subtitleContent }}</pre>
        </div>
        <div v-else class="subtitle-error">
          <p>无法加载字幕内容或字幕为空</p>
        </div>
        <div class="subtitle-actions">
          <el-button size="small" type="primary" @click="downloadSubtitle"
            :disabled="!hasValidSubtitlePath(currentSubtitleFile)">
            下载字幕文件
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 确认选择对话框 -->
    <el-dialog v-model="confirmDialogVisible" title="确认添加" width="400px" append-to-body>
      <p>确定要添加选中的 {{ selectedHistoryItems.length }} 个音频文件到当前音频吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addSelectedAudiosToCurrentList">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 音频上传对话框 -->
    <audio-uploader 
      v-model:visible="audioUploaderVisible" 
      :default-group-id="selectedGroupId"
      @upload-success="handleUploadSuccess" />
  </div>
</template>

<script>
import { ref, defineComponent, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import mergeService from '@/views/Mergeview/services/mergeService';
import AudioUploader from './AudioUploader.vue';
import { Upload, Refresh } from '@element-plus/icons-vue';

export default defineComponent({
  name: 'AudioGroupTable',
  components: {
    AudioUploader
  },
  props: {
    audioGroup: {
      type: Array,
      default: () => []
    },
    groupId: {
      type: String,
      default: ''
    }
  },
  emits: ['selection-change', 'update:groupId', 'add-audios'],
  setup(props, { emit }) {
    const route = useRoute();
    const urlHasGroupId = computed(() => !!route.query.group_id);

    const audioTable = ref(null);
    const historyTable = ref(null);
    const selectedItems = ref([]);
    const selectedHistoryItems = ref([]);
    const groupIdModel = ref(props.groupId);
    const audioPlayerVisible = ref(false);
    const audioPlayer = ref(null);
    const currentAudioFile = ref(null);
    const currentAudioUrl = ref('');

    // 替换el-tabs以自定义实现
    const currentTabName = ref('current');
    const historyAudios = ref([]);
    const historySearchQuery = ref('');
    const confirmDialogVisible = ref(false);

    // 新增字幕相关变量
    const subtitlePreviewVisible = ref(false);
    const currentSubtitleFile = ref(null);
    const subtitleContent = ref('');
    const subtitleLoading = ref(false);

    // 分页信息
    const paginationInfo = ref({
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      totalPages: 0
    });

    // 音频上传对话框状态
    const audioUploaderVisible = ref(false);
    const selectedGroupId = ref('');
    
    // 切换标签的方法
    const switchTab = (tabName) => {
      currentTabName.value = tabName;

      // 如果切换到历史记录标签，加载数据
      if (tabName === 'history') {
        loadHistoryAudios();
      }
    };

    // 过滤的历史音频
    const filteredHistoryAudios = computed(() => {
      if (!historySearchQuery.value) {
        return historyAudios.value;
      }

      const query = historySearchQuery.value.toLowerCase();
      return historyAudios.value.filter(audio =>
        audio.filename.toLowerCase().includes(query) ||
        (getMetaDataText(audio.meta_data).toLowerCase().includes(query))
      );
    });

    // 同步分组ID
    watch(() => props.groupId, (newVal) => {
      groupIdModel.value = newVal;
    });

    // 计算属性，将audioGroup属性值传递给内部使用
    const audioData = computed(() => props.audioGroup || []);

    // 处理当前表格选择变化
    const handleSelectionChange = (selection) => {
      selectedItems.value = selection;
      emit('selection-change', selection);
    };

    // 处理历史表格选择变化
    const handleHistorySelectionChange = (selection) => {
      selectedHistoryItems.value = selection;
    };

    // 处理历史页面变化
    const handleHistoryPageChange = (page) => {
      paginationInfo.value.currentPage = page;
      loadHistoryAudios(page);
    };

    // 当前音频表格全选功能
    const selectAll = () => {
      if (audioTable.value) {
        audioData.value.forEach(row => {
          audioTable.value.toggleRowSelection(row, true);
        });
      }
    };

    // 当前音频表格取消全选功能
    const deselectAll = () => {
      if (audioTable.value) {
        audioTable.value.clearSelection();
      }
    };

    // 历史表格全选功能
    const selectAllHistory = () => {
      if (historyTable.value) {
        filteredHistoryAudios.value.forEach(row => {
          historyTable.value.toggleRowSelection(row, true);
        });
      }
    };

    // 历史表格取消全选功能
    const deselectAllHistory = () => {
      if (historyTable.value) {
        historyTable.value.clearSelection();
      }
    };

    // 清空当前音频组
    const clearCurrentAudioGroup = () => {
      emit('update:groupId', '');
    };

    // 获取文件URL
    const getAudioUrl = (file) => {
      if (!file || !file.audio_path) return '';

      // 提取public之后的路径
      const pathParts = file.audio_path.split('\\');
      const publicIndex = pathParts.findIndex(part => part === 'public');

      if (publicIndex !== -1) {
        // 构建URL路径
        const relativePath = pathParts.slice(publicIndex).join('/');
        return `${window.location.origin}/${relativePath}`;
      }

      // 如果没有找到public路径，使用原始路径但替换反斜杠
      return `${window.location.origin}/public/audios/${file.filename}`;
    };

    // 新增获取字幕文件URL函数
    const getSubtitleUrl = (file) => {
      if (!file || !file.subtitle_path) return '';

      // 提取public之后的路径
      const pathParts = file.subtitle_path.split('\\');
      const publicIndex = pathParts.findIndex(part => part === 'public');

      if (publicIndex !== -1) {
        // 构建URL路径
        const relativePath = pathParts.slice(publicIndex).join('/');
        return `${window.location.origin}/${relativePath}`;
      }

      // 如果没有找到public路径，使用文件名作为替代
      return `${window.location.origin}/public/subtitles/${file.filename.replace(/\.[^.]+$/, '.srt')}`;
    };

    // 修改检查音频路径函数
    const hasValidAudioPath = (file) => {
      return file && file.audio_path;
    };

    // 新增检查字幕路径函数
    const hasValidSubtitlePath = (file) => {
      return file && file.subtitle_path;
    };

    // 修改检查是否可以播放音频
    const canPlayAudio = (file) => {
      return hasValidAudioPath(file);
    };

    // 修改播放音频
    const playAudio = (file) => {
      if (!canPlayAudio(file)) {
        ElMessage.warning('该音频文件不可播放');
        return;
      }

      currentAudioFile.value = file;
      currentAudioUrl.value = getAudioUrl(file);
      audioPlayerVisible.value = true;

      // 在对话框打开后尝试播放
      setTimeout(() => {
        if (audioPlayer.value) {
          audioPlayer.value.play()
            .catch(error => {
              console.error('音频播放失败:', error);
              ElMessage.error('音频播放失败，请检查文件是否可访问');
            });
        }
      }, 300);
    };

    // 修改下载音频
    const downloadAudio = (file) => {
      if (!hasValidAudioPath(file)) {
        ElMessage.warning('该文件没有有效的音频路径');
        return;
      }

      const url = getAudioUrl(file);
      const a = document.createElement('a');
      a.href = url;
      a.download = file.filename || 'audio';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      ElMessage.success('开始下载音频文件');
    };

    // 新增预览字幕函数
    const previewSubtitle = async (file) => {
      if (!hasValidSubtitlePath(file)) {
        ElMessage.warning('该文件没有有效的字幕路径');
        return;
      }

      currentSubtitleFile.value = file;
      subtitleContent.value = '';
      subtitleLoading.value = true;
      subtitlePreviewVisible.value = true;

      try {
        // 尝试加载字幕内容
        const response = await fetch(getSubtitleUrl(file));
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        const text = await response.text();
        subtitleContent.value = text;
      } catch (error) {
        console.error('获取字幕内容失败:', error);
        ElMessage.error('获取字幕内容失败，请检查文件是否可访问');
        subtitleContent.value = '';
      } finally {
        subtitleLoading.value = false;
      }
    };

    // 新增下载字幕函数
    const downloadSubtitle = (file) => {
      if (!currentSubtitleFile.value || !hasValidSubtitlePath(currentSubtitleFile.value)) {
        ElMessage.warning('没有有效的字幕文件可下载');
        return;
      }

      const url = getSubtitleUrl(currentSubtitleFile.value);
      const a = document.createElement('a');
      a.href = url;
      a.download = currentSubtitleFile.value.filename.replace(/\.[^.]+$/, '.srt') || 'subtitle.srt';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      ElMessage.success('开始下载字幕文件');
    };

    // 确认选择历史音频
    const confirmHistorySelection = () => {
      if (selectedHistoryItems.value.length === 0) {
        ElMessage.warning('请先选择要添加的音频文件');
        return;
      }
      confirmDialogVisible.value = true;
    };

    // 将选中的历史音频添加到当前列表
    const addSelectedAudiosToCurrentList = () => {
      // 发出事件，通知父组件添加选中的音频
      emit('add-audios', selectedHistoryItems.value);
      confirmDialogVisible.value = false;
      switchTab('current'); // 切换回当前音频标签页
      // 清除历史选择
      deselectAllHistory();
      ElMessage.success(`已添加 ${selectedHistoryItems.value.length} 个音频文件`);
    };

    // 加载历史音频文件
    const loadHistoryAudios = async (page = 1) => {
      try {
        // 调用API获取历史音频文件
        const response = await mergeService.getAudioHistory(page, 10);

        if (response && response.success && response.data) {
          // 使用服务器返回的数据
          historyAudios.value = response.data.records || [];

          // 更新分页信息
          if (response.data.pagination) {
            paginationInfo.value = {
              currentPage: response.data.pagination.page || 1,
              pageSize: response.data.pagination.page_size || 10,
              totalCount: response.data.pagination.total_count || 0,
              totalPages: response.data.pagination.total_pages || 1
            };
          }
        } else {
          console.error('获取历史音频数据失败', response);
          ElMessage.error('获取历史音频数据失败');
        }
      } catch (error) {
        console.error('加载历史音频失败:', error);
        ElMessage.error('加载历史音频失败');
      }
    };

    // 解析meta_data字符串为对象
    const parseMetaData = (metaDataStr) => {
      try {
        if (!metaDataStr) return null;
        // 如果已经是对象，直接返回
        if (typeof metaDataStr === 'object') return metaDataStr;
        // 否则尝试解析JSON字符串
        return JSON.parse(metaDataStr);
      } catch (e) {
        console.error('解析meta_data失败', e);
        return null;
      }
    };

    // 获取meta_data中的语言信息
    const getLanguageTag = (metaDataStr) => {
      const metaData = parseMetaData(metaDataStr);
      if (!metaData || !metaData.language) return '';

      // 返回简短的语言标签
      return `[${metaData.language}]`;
    };

    // 获取meta_data中的时长信息，格式化为 分:秒
    const getDuration = (metaDataStr) => {
      const metaData = parseMetaData(metaDataStr);
      if (!metaData || !metaData.duration) return '-';

      const seconds = parseInt(metaData.duration);
      if (isNaN(seconds)) return '-';

      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins}:${secs.toString().padStart(2, '0')}`;
    };

    const getMetaDataText = (metaDataStr) => {
      const metaData = parseMetaData(metaDataStr);
      if (!metaData) return '';
      return metaData.text || metaData.name || '';
    };

    // 打开音频上传对话框
    const openAudioUploader = (groupId = '') => {
      selectedGroupId.value = groupId;
      audioUploaderVisible.value = true;
    };
    
    // 处理上传成功
    const handleUploadSuccess = (data) => {
      ElMessage.success('音频上传成功');
      loadHistoryAudios()
    };

    onMounted(() => {
      // 如果URL有group_id，默认显示当前音频标签，否则显示历史记录标签
      currentTabName.value = urlHasGroupId.value || props.groupId ? 'current' : 'history';

      // 如果默认显示历史记录，则加载数据
      if (currentTabName.value === 'history') {
        loadHistoryAudios();
      }
    });

    return {
      audioTable,
      historyTable,
      selectedItems,
      selectedHistoryItems,
      groupIdModel,
      audioData,
      handleSelectionChange,
      handleHistorySelectionChange,
      getMetaDataText,
      selectAll,
      deselectAll,
      selectAllHistory,
      deselectAllHistory,
      playAudio,
      downloadAudio,
      canPlayAudio,
      audioPlayerVisible,
      audioPlayer,
      currentAudioFile,
      currentAudioUrl,
      urlHasGroupId,
      // 修改部分
      currentTabName,
      switchTab,
      historyAudios,
      historySearchQuery,
      filteredHistoryAudios,
      confirmDialogVisible,
      clearCurrentAudioGroup,
      confirmHistorySelection,
      addSelectedAudiosToCurrentList,
      handleHistoryPageChange,
      paginationInfo,
      getAudioUrl,
      getSubtitleUrl,
      hasValidAudioPath,
      hasValidSubtitlePath,
      subtitlePreviewVisible,
      currentSubtitleFile,
      subtitleContent,
      subtitleLoading,
      previewSubtitle,
      downloadSubtitle,
      parseMetaData,
      getLanguageTag,
      getDuration,
      getMetaDataText,
      audioUploaderVisible,
      selectedGroupId,
      openAudioUploader,
      handleUploadSuccess,
      Upload, // 添加Upload图标
    };
  }
});
</script>

<style scoped>

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.selection-count {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.group-id-display {
  font-size: 14px;
  color: #409EFF;
  background-color: #ecf5ff;
  padding: 5px 10px;
  border-radius: 4px;
  border: 1px solid #d9ecff;
}

.table-actions,
.history-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.audio-player-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
}

.audio-info {
  width: 100%;
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.audio-info p {
  margin: 5px 0;
  color: #606266;
}

.empty-state {
  padding: 40px 0;
}

/* 新增样式 - 自定义标签 */
.custom-tabs {
  display: flex;
  flex-direction: column;
}

.tab-headers {
  display: flex;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.tab-header {
  padding: 10px 20px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  margin-right: 10px;
  font-weight: 500;
  color: #606266;
  transition: all 0.3s;
}

.tab-header.active {
  border-bottom: 2px solid #409EFF;
  color: #409EFF;
}

.tab-content {
  min-height: 450px;
}

.history-search {
  margin-bottom: 15px;
}

.language-tag {
  display: inline-block;
  background-color: #409EFF;
  color: white;
  padding: 0 5px;
  border-radius: 4px;
  margin-right: 5px;
  font-size: 12px;
  font-weight: bold;
}

/* 可以根据不同语言设置不同颜色 */
.language-tag.Thai {
  background-color: #67C23A;
}

.language-tag.English {
  background-color: #E6A23C;
}

.language-tag.Vietnamese {
  background-color: #F56C6C;
}

.language-tag.Korean {
  background-color: #909399;
}

.group-table-container {
  padding-top: 10px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  margin: 0;
}

.actions {
  display: flex;
  gap: 10px;
}
</style>